package com.ts.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.ts.entity.User;
import com.ts.util.DB;

@Results({
	@Result(name="login_success",location="/home.jsp",type="redirect"),
	@Result(name="login_input",location="/index.jsp"),
	@Result(name="register_success",location="/index.jsp",type="redirect"),
	@Result(name="logout_success",location="/index.jsp",type="redirect")
})
public class UserAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private User user;
	private Connection connection;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;
	private final String LOGIN = "select * from user where username=? and password=?";
	private final String REGISTER = "insert into user values(null, ?, ?)";

	/** 用户登录 */
	@Action("user_login")
	public String login() throws Exception {

		connection = DB.getConnection();
		preparedStatement = connection.prepareStatement(LOGIN);
		preparedStatement.setString(1, user.getUsername());
		preparedStatement.setString(2, user.getPassword());
		resultSet = preparedStatement.executeQuery();
		boolean b = resultSet.next();
		DB.close(resultSet, preparedStatement, connection);
		if (b) {
			return "login_success";
		} else {
			return "login_input";
		}
	}

	/** 用户注册 */
	@Action("user_register")
	public String register() throws Exception {
		connection = DB.getConnection();
		preparedStatement = connection.prepareStatement(REGISTER);
		preparedStatement.setString(1, user.getUsername());
		preparedStatement.setString(2, user.getPassword());
		preparedStatement.executeUpdate();
		DB.close(null, preparedStatement, connection);
		return "register_success";
	}
	/** 用户注销 */
	@Action("user_logout")
	public String logout() {
		getSession().clear();
		return "logout_success";

	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}
